package com.xzit.headline.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.VideoView;

import com.xzit.headline.R;

public class SplashActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        //1.布局 videoView
        //2.准备图片与视频的资源
        //3.开始播放视频
        stratPlayVideo();
        //4.监听是否点击了跳转按钮
        ListenerJumpBtn();
        //5.将画面设置成屏幕大小
        setVideoSize();
    }

    private void setVideoSize() {
        //5.1.获取屏幕的尺寸
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        //5.2.创建布局参数
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(metrics.widthPixels, metrics.heightPixels);
        //5.3.设置给VideoView
        videoView.setLayoutParams(params);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

    }

    private boolean isJump = false;

    private void ListenerJumpBtn() {
        Button jump = findViewById(R.id.jump);
        jump.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isJump = true;
                //结束播放
                finish();
                //跳转到主页面
                startActivity(new Intent(SplashActivity.this, MainActivity.class));
            }
        });
    }

    private VideoView videoView;

    private void stratPlayVideo() {
        //播放地址
        Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.video);
        //获取页面视频播放组件
        videoView = findViewById(R.id.videoView);
        //设置视频的播放uri
        videoView.setVideoURI(uri);
        //开始播放
        videoView.start();

        //设置播放监听
        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if (!isJump) {
                    //结束activity
                    finish();
                    //跳转到首页界面activity
                    startActivity(new Intent(SplashActivity.this, MainActivity.class));
                }
            }
        });
    }
}
